// pages/userSignIn/userSignIn.
var IDpass = true;
var phonePass = true;
var namePass = true;
const db=wx.cloud.database()
const app=getApp()
var isConfirm
Page({
  data: {
    //isThr
    major:['农业咨询','法律咨询', '心理咨询' ,'文娱策划','医疗咨询','艺术咨询','环境养护'],
    question:['邻里互助','儿童助学','农业生产','照顾老人'],
    culture:[ '敬老爱老','科学普及','文明乡村','信息普及','政策普及'],
    residemajor:'',
    residequestion:'',
    resideculture:'',
    //isThr
    value: "1",
    idcountry: ['中国', '中国香港', '中国澳门', '中国台湾'],
    idType: ['内地居民身份证', '香港居民身份证', '澳门居民身份证', '台湾居民身份证'],
    index: "",
    isOne: true, isTwo: false, isThr: false,
    code: "",  phone: "", Name: "", ID:"",  region: ['', '', ''],
    nameErrMes: "", IDNumErrMes: "",
    phoneErrMes: "", verifyCodeErrMes: "", homeErrMes: "", IDErrMes: "",
    isConfirm:false,
  },
  //检测姓名（是否是汉字）
  getName(e) {
    namePass = true;
    console.log(e.detail)
    this.setData({ Name: e.detail })
    let reg = /^[\u2E80-\u9FFF]+$/;
    console.log(reg.test(e.detail))
    if (!reg.test(e.detail)) {
      console.log("执行")
      this.setData({ nameErrMes: "姓名格式错误" })
      namePass = false;
    }
    else {
      this.setData({ nameErrMes: "" })
      namePass = true;
    }
  },
  //获取身份证号
  getIDNum(e) {
    console.log(e.detail);
    this.setData({ code: e.detail })
    this.identityCodeValid()
  },
  //检测身份证号的合法性
  identityCodeValid() {
    IDpass = true;
    var city = {
      11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 "
    };
    var idCardReg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/g;
    var code = this.data.code
    if (!code || !idCardReg.test(code)) {
      this.setData({ IDNumErrMes: "身份证号码错误，请重新输入" })
      IDpass = false;
    } else if (!city[code.substr(0, 2)]) {
      this.setData({ IDNumErrMes: "身份证号码错误，请重新输入" })
      IDpass = false;
    } else {
      //18位身份证需要验证最后一位校验位
      if (code.length == 18) {
        code = code.split('');
        //∑(ai×Wi)(mod 11)
        //加权因子
        var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        //校验位
        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
        var sum = 0;
        var ai = 0;
        var wi = 0;
        for (var i = 0; i < 17; i++) {
          ai = code[i];
          wi = factor[i];
          sum += ai * wi;
        }
        var last = parity[sum % 11];
        if (parity[sum % 11] != code[17]) {
          this.setData({ IDNumErrMes: "身份证号码错误，请重新输入" })
          IDpass = false;
        }
      }
    }
    if (IDpass) this.setData({ IDNumErrMes: "" })
  },
  //进入第二步
  enterSec() {
    this.identityCodeValid()
    if (this.data.Name == "")
      this.setData({ nameErrMes: "姓名格式错误" })
    if (IDpass && namePass) {
      this.setData({
        isOne: false,
        isTwo: true
      })
    }
  },
  //返回上一步
  return() {
    if (this.data.isTwo)
      this.setData({
        isOne: true,
        isTwo: false
      })
    if (this.data.isThr)
      this.setData({
        isTwo: true,
        isThr: false
      })
  },
  enterThr() {
    this.checkphone();
    if (this.data.region[0] == "") {
      this.setData({ homeErrMes: "请选择家乡" })
    }
    else this.setData({ homeErrMes: "" })
    if (this.data.ID == "")
      this.setData({ IDErrMes: "请获取ID" })
    else this.setData({ IDErrMes: "" })
    if (phonePass && phonePass) {
      this.setData({
        isThr: true,
        isTwo: false,
      })
    }
  },
  checkphone() {
    phonePass = true;
    var phoneReg = /^1[3456789]\d{9}$/
    if (!phoneReg.test(this.data.phone)) {
      this.setData({ phoneErrMes: "手机号码格式错误,请重新输入" })
      phonePass = false;
    }
    else {
      this.setData({ phoneErrMes: "" })
      phonePass = true;
    }
  },
  getPhone(e) {
    this.setData({ phone: e.detail })
    this.checkphone()
  },
  getRandomCode(length) {
    if (length > 0) {
      var data = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
      var nums = "";
      for (var i = 0; i < length; i++) {
        var d = Math.random()
        var r = parseInt(Math.random() * 10);
        nums += data[r];
      }
      return nums;
    } else {
      return false;
    }
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  getID(length) {
    // 13
    var time = new Date().getTime()
    var timeString = time.toString()
    var timeRandom = timeString.substr(timeString.length - 2)
    return (timeRandom + this.getRandomCode(length));
  },
  idGet() {
    let ID = this.getID(8)
    console.log("Id", ID)
    this.setData({
      ID: ID
    })
  },
  getPhoneNumber(e){
    console.log(e)
    wx.cloud.callFunction({
      name: 'getPhoneNum',
      data: {
          code: e.detail.code
      },
      success: (res) => {
          console.log('调用云函数', res)
      }
  })
  },
//   getPhoneNumber(e){
//     console.log("枕芯")
//     var ivObj = e.detail.iv
//     var telObj = e.detail.encryptedData
//     var codeObj = "";
//     var that = this;
//     //------执行Login---------
//     wx.login({
//      success: res => {
//        console.log("res1",res)
//       console.log('code转换', res.code);
//  　　　　　　//用code传给服务器调换session_key
//       wx.request({
//        url: 'https://mp.weixin.qq.com', //接口地址
//        data: {
//         appid: "wx2350dfaf14adf1b3",
//         secret: "a7cda9603b38884cea8a7c67b9c5c5fc",
//         code: res.code,
//         encryptedData: telObj,
//         iv: ivObj
//        },
//        success: function (res) {
//          console.log(res)
//         var phoneObj = res.data.phoneNumber;
//         console.log("手机号=", phoneObj)
//        }
//       })
//       }
//     })
//   },
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  signIn(){
    if(!this.data.isConfirm)
    {
      wx.showToast({
        title: '请先勾选同意隐私协议',
        icon:"none"
      })
    }
    else{
      wx.cloud.callFunction({
        name:"updateUserInfo",
        data:{
           action:"userInfo",
           Name:this.data.Name,
           code:this.data.code,
           ID:this.data.ID,
           phone:this.data.phone,
           region:this.data.region,
           openid:app.globalData.openid
     }
    })
     .then(res=>{
      console.log("注册成功",res)
      wx.switchTab({
        url: '../../me/me',
      })
    })
    wx.cloud.callFunction({
      name:"updateUserInfo",
      data:{
        action:"point",
         openid:app.globalData.openid,
         time:app.getTime(5),
         reason:"志愿者注册",
         pointDetail:50,
      }
    })
    .then(res=>{
        console.log("志愿者注册更新积分成功",res)
    })
    wx.cloud.callFunction({
      name:"updateUserInfo",
      data:{
         action:"exe",
         openid:app.globalData.openid,
         time:app.getTime(5),
         reason:"志愿者注册",
         exeDetail:200,
      }
    })
    .then(res=>{
      console.log("志愿者注册更新经验值成功",res)
    })
    }
    app.updateAPPuserInfo()
  },

  tapToConfirm(){
    this.setData({
      isConfirm:!isConfirm
    })
    isConfirm=!isConfirm
  },
  PrivatePro(){
     wx.navigateTo({
       url: '../../PrivatePro/PrivatePro',
     })

  },
  //专业对口
  majorChoose(e){
    console.log('majorChoose',this.data.major[parseInt(e.detail.value)] );
    this.setData({residemajor:this.data.major[parseInt(e.detail.value)]})
  },
  //问题解决
  questionChoose(e){
    console.log('questionChoose',this.data.question[parseInt(e.detail.value)] );
    this.setData({residequestion:this.data.question[parseInt(e.detail.value)]});
  },
  //文化建设
  cultureChoose(e){
    console.log('cultureChoose',this.data.culture[parseInt(e.detail.value)] );
    this.setData({resideculture:this.data.culture[parseInt(e.detail.value)]});
  },
  onLoad: function (options) {
    app.editTabbar()
    console.log("此志愿者的openid",app.globalData.openid)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})